package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhentao.mapper.WmUserMapper;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.service.WmUserService;
import com.zhentao.utils.common.AppJwtUtil;
import com.zhentao.model.wemedia.dto.WmLoginDto;
import com.zhentao.model.wemedia.pojo.WmUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl implements WmUserService {
    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public ResponseResult login(WmLoginDto dto) {
//        参数校验
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账号或者密码为空");
        }
//        根据账号查询用户是否存在
        QueryWrapper<WmUser> wmUserQueryWrapper = new QueryWrapper<>();
        wmUserQueryWrapper.lambda().eq(WmUser::getName, dto.getName());
        WmUser wmUser = wmUserMapper.selectOne(wmUserQueryWrapper);
//        如果没查到
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账号不存在");
        }
//        查到账号之后校验密码
        String salt = wmUser.getSalt();
        String password = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes(StandardCharsets.UTF_8));
//        校验成功
        if (password.equals(wmUser.getPassword())) {
            wmUser.setPhoto(wmUser.getPhone());
//            登录成功，生成token
            String token = AppJwtUtil.getToken(wmUser.getId().longValue());
//            创建一个map集合
            Map<String, Object> map = new HashMap<>();
//            将token以键值对的方式存储到map中
            map.put("token", token);
//            密码不能传给前端
            wmUser.setPassword(null);
            wmUser.setSalt(null);
//            把用户信息以键值对方式存储map集合中
            map.put("user", wmUser);
            map.put("photo", wmUser.getPhone());
            return ResponseResult.okResult(map);
        }else {
//            否则就是登录失败，密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
        }
    }
}
